
<template>
    <div>
        <el-row class="tigan">
            试题题干：
            <div class="editorBox">
                <TinymceEditor1 class="tiganIpt" ref="editor" v-model="modelValue.subjectEditorValue" :height="200" />
            </div>
        </el-row>
        <el-row>
            <el-col>
                <header>答案选项 <span style="margin-left: 25px;"> 是否多连 <el-switch
                            v-model="props.modelValue.LXvalModel.isAnyChange" @change="elSwitchChange" /></span></header>
            </el-col>
            <el-col>
                <article>
                    <!-- 答案输入列表 -->
                    <section style="display: flex;">
                        <ul style="width:40%">
                            <li v-for="(item, index) in props.modelValue.LXvalModel.list.left" :key="item.aw"
                                class="liStyle">
                                <aside style="width: 90%;display: flex;justify-content: space-between;">
                                    <div style="width: 100%;display: flex;align-items: center;">
                                        <div>{{ index + 1 }}.</div>
                                        <TinymceEditor style="width: 98%;margin-left: 5px;" class="tiganIpt" ref="editor"
                                            v-model="item.text" :height="57" @blur="onChange(item, '1', $event)" />
                                    </div>
                                </aside>
                                <span class="delClass">
                                    <el-tooltip effect="light" content="删除" placement="top-start">
                                        <svg class="icon" aria-hidden="true" @click="delLineList(item, '1')">
                                            <use xlink:href="#icon-shanchu1"></use>
                                        </svg>
                                    </el-tooltip>
                                </span>
                            </li>

                        </ul>
                        <ul style="width:40%">
                            <li v-for="(item, index) in props.modelValue.LXvalModel.list.right" :key="item.aw"
                                class="liStyle">
                                <aside style="width: 90%;display: flex;justify-content: space-between;">
                                    <div style="width: 100%;display: flex;align-items: center;">
                                        <div>{{ letter[index] }}.</div>
                                        <TinymceEditor style="width: 98%;margin-left: 5px;" class="tiganIpt" ref="editor"
                                            @blur="onChange(item, '2', $event)" v-model="item.text" :height="57" />
                                    </div>
                                </aside>
                                <span class="delClass">
                                    <el-tooltip effect="light" content="删除" placement="top-start">
                                        <svg class="icon" aria-hidden="true" @click="delLineList(item, '2')">
                                            <use xlink:href="#icon-shanchu1"></use>
                                        </svg>
                                    </el-tooltip>
                                </span>
                            </li>
                        </ul>
                    </section>
                    <!-- 选择答案 -->
                </article>

            </el-col>
            <el-col>
                <div class="borderDix"></div>
            </el-col>
            <el-col>
                <el-button type="primary" plain :icon="Plus" text @click="addLineList">添加选项</el-button>
            </el-col>
            <el-col style="margin-top: 10px;">
                <header>正确答案： <span>（点击左侧模块与右侧相连配对正确答案）</span> </header>
            </el-col>
            <el-col>
                <article class="answerDisplay" id="answerDisplayId" :style="getHeight()">
                    <!-- 问题 -->
                    <div v-for="(item, index) in props.modelValue.LXvalModel.list.left" :id="item.aw" :key="index"
                        :class="leftClass(item)" :style="leftStyleClass(index)" @click="drawLeft(item)">
                        <span v-html="item.text"></span>
                    </div>
                    <!-- 答案 -->
                    <div v-for="(item, index) in props.modelValue.LXvalModel.list.right" :id="item.aw" :key="index"
                        :style="rightStyleClass(index)" @click="drawRight(item)"
                        :class="item.status == 2 ? 'lineToStatus' : ''">
                        <span v-html="item.text"></span>
                    </div>

                </article>
            </el-col>

        </el-row>
    </div>
</template>
<script setup>
import { getCurrentInstance, toRefs, ref, reactive, onMounted, onBeforeUnmount, watch } from 'vue'
import {
    Plus,
} from '@element-plus/icons-vue'
import TinymceEditor from '../component/Editor/indexLianxian.vue';
import TinymceEditor1 from '../component/Editor/index.vue'
import '../../iconFont/iconfont'
import { nanoIds } from '../../utils/auth.js'
const letter = reactive(['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']);
const props = defineProps({
    modelValue: {
        type: [String, Object, Array],
        default: null,
    }
});
let ids = nanoIds(6);

const beginLeft = {
    right: null,
    top: null
};
const endRight = {
    left: null,
    top: null
};
const isAnyLine = ref(false)

const _STATUS = 0; // 未选中状态
const _LINELEFT = 1; // 左侧选中
const STATE_CONNECTION = 2; // 连线状态
let selectList = null;



onMounted(() => {
    onInitList()

});

const elSwitchChange = (val) => {
    if (!val) {
        props.modelValue.LXvalModel.connections = [];
        props.modelValue.LXvalModel.list.left = props.modelValue.LXvalModel.list.left.map(item => {
            if (item.lineId) {
                item.lineId[1].map(itemChild => {
                    _rmAnswerLine([item.aw, itemChild])
                })
            }
            return {
                "aw": item.aw,
                "text": item.text,
                "status": _STATUS,
                "active": 0,
                "height": item.height,
                "lineId": null
            }
        });
        props.modelValue.LXvalModel.list.right = props.modelValue.LXvalModel.list.right.map(item => {
            return {
                "aw": item.aw,
                "text": item.text,
                "status": _STATUS,
                "active": 0,
                "height": item.height,
                "lineId": null
            }
        });
        // onInitList();
    }
};
/** 初始化 */
const onInitList = () => {
    if (!props.modelValue.LXvalModel.connections.length) return;
    props.modelValue.LXvalModel.connections.map(item => {
        setTimeout(() => {
            let leftDom = document.getElementById(item.id);
            beginLeft.right = leftDom.offsetWidth + 2;
            beginLeft.top = (leftDom.offsetHeight / 2) + leftDom.offsetTop;
            item.result.map(itemChild => {
                let rightDom = document.getElementById(itemChild);
                endRight.left = rightDom.offsetLeft - 2;
                endRight.top = (rightDom.offsetHeight / 2) + rightDom.offsetTop;
                _drawLine(item.id, itemChild)
            })

        }, 0)

    })
};

// 获取最大高度
const getHeight = () => {
    let height = 0;
    let height2 = 0;
    props.modelValue.LXvalModel.list.left.map(item => {
        height += item.height + 20
    })
    props.modelValue.LXvalModel.list.right.map(item => {
        height2 += item.height + 20
    });
    return {
        "min-height": height >= height2 ? `${height}px` : `${height2}px`
    }

};

/** 左侧div分布样式 */
const leftStyleClass = (index) => {
    let top = 0;
    let left = 0;
    for (let i = 0; i < index; i++) {
        top += props.modelValue.LXvalModel.list.left[i].height + 20
    }
    return {
        "top": top + 'px',
        "left": left
    }
}

/** 右侧div分布样式 */
const rightStyleClass = (index) => {
    let top = 0;
    let right = 0;
    for (let i = 0; i < index; i++) {
        top += props.modelValue.LXvalModel.list.right[i].height + 20
    }
    return {
        "top": top + 'px',
        "right": right
    }
};

/** 点击左侧问题事件 */
const drawLeft = (event) => {
    if (selectList && selectList.aw != event.aw) {
        selectList.active = _STATUS
    };
    event.active = _LINELEFT;
    selectList = event;
    let leftDom = document.getElementById(event.aw);
    beginLeft.right = leftDom.offsetWidth + 2;
    beginLeft.top = (leftDom.offsetHeight / 2) + leftDom.offsetTop;
};

/** 右侧点击 划线 */
const drawRight = (event) => {
    if (!selectList?.active) return;
    let rightDom = document.getElementById(event.aw);
    endRight.left = rightDom.offsetLeft - 2;
    endRight.top = (rightDom.offsetHeight / 2) + rightDom.offsetTop;
    const _addDraw = () => { //  多联划线
        _drawLine(selectList.aw, event.aw);
        // 判断左边选的是否有连接
        let isLine = props.modelValue.LXvalModel.connections.filter(item => item.id == selectList.aw);
        if (!isLine.length) {
            props.modelValue.LXvalModel.connections.push({
                "id": selectList.aw,
                "result": [event.aw]
            });
        } else {
            if (isLine[0].result.includes(event.aw)) return;
            isLine[0].result.push(event.aw);
        };
    };

    const drawIsAnyLineFn = () => {
        //     // 创建  即 只要生成线 就会走下面内容
        selectList.lineId = [selectList.aw, [event.aw]];
        event.lineId = [[selectList.aw], event.aw];
        event.status = selectList.status = STATE_CONNECTION
        _drawLine(selectList.aw, event.aw);
        props.modelValue.LXvalModel.connections.push({
            "id": selectList.aw,
            "result": [event.aw]
        });
    }

    const isAnyLineFn = {
        '1': () => { // 多联
            if (selectList.lineId) { // 首先判断左边是否有连线 即 lineId  存在
                let objIsLine = {
                    "1": () => { // 已包含 此刻要删除连线
                        selectList.lineId[1] = selectList.lineId[1].filter(item => item != event.aw);

                        event.lineId[0] = event.lineId[0].filter(item => item != selectList.aw);

                        _rmAnswerLine([selectList.aw, event.aw]);
                        let isLine = props.modelValue.LXvalModel.connections.filter(item => item.id == selectList.aw);
                        isLine[0].result = isLine[0].result.filter(item => item != event.aw);
                        if (event.lineId[0].length) {
                            event.status = STATE_CONNECTION
                        } else {
                            event.status = _STATUS
                        };
                        if (selectList.lineId[1].length) {
                            selectList.status = STATE_CONNECTION
                        } else {
                            selectList.status = _STATUS
                        };

                    },
                    "2": () => {// 未包含 添加连线
                        selectList.lineId[1].push(event.aw)
                        //  右边lineId是否存在 ，未存在添加 已存在push；
                        if (event.lineId) {
                            event.lineId[0].push(selectList.aw)
                        } else {
                            event.lineId = [[selectList.aw], event.aw]
                        };
                        selectList.status = event.status = STATE_CONNECTION;
                        _addDraw()

                    }
                };
                // 已经连线判断左侧是否与右侧勾选 1 勾选  2 未勾选
                let isLine = selectList.lineId[1].includes(event.aw) ? "1" : "2";
                objIsLine[isLine]();
            } else { // 没有连线的情况 直接划线
                // 给左侧添加lineId ，并且并且判断·右侧是否连线 连线的话push，没连线创建
                selectList.lineId = [selectList.aw, [event.aw]];
                if (event.lineId) {
                    event.lineId[0].push(selectList.aw)
                } else {
                    event.lineId = [[selectList.aw], event.aw]
                }
                selectList.active = _STATUS;
                //  设置当前连线数据状态
                selectList.status = event.status = STATE_CONNECTION;
                _addDraw()
            };
        },
        '2': () => { // 单联

            // 左右都没连 左右都连了 左右分别连了一个
            // 左右都连线
            if (selectList.status == event.status && event.status == STATE_CONNECTION) {
                // 是否是互联的状态 如果是就取消
                if (selectList.lineId[1][0] == event.aw) {
                    // console.log(111);
                    _rmAnswerLine([selectList.aw, event.aw]);
                    selectList.lineId = event.lineId = null;
                    selectList.status = event.status = _STATUS;
                    props.modelValue.LXvalModel.connections = props.modelValue.LXvalModel.connections.filter(item => item.id != selectList.aw);
                } else {
                    // console.log(2222,selectList,event);
                    _rmAnswerLine([selectList.lineId[0], selectList.lineId[1][0]]);//先删除左边连线
                    _rmAnswerLine([event.lineId[0][0], event.lineId[1]]);//先删除右边连线
                    props.modelValue.LXvalModel.connections = props.modelValue.LXvalModel.connections.filter(item => (item.id != selectList.lineId[0] && item.id != event.lineId[0][0]));
                    drawIsAnyLineFn()
                }
            } else if (selectList.status == STATE_CONNECTION || event.status == STATE_CONNECTION) { // 左右 只有一个连线
                if (selectList.status == STATE_CONNECTION) {
                    // console.log(333);
                    _rmAnswerLine([selectList.lineId[0], selectList.lineId[1][0]]);//先删除左边连线
                    props.modelValue.LXvalModel.connections = props.modelValue.LXvalModel.connections.filter(item => (item.id != selectList.lineId[0]));
                    drawIsAnyLineFn()
                } else {
                    // console.log(44444);
                    _rmAnswerLine([event.lineId[0][0], event.lineId[1]]);//先删除右边连线
                    props.modelValue.LXvalModel.connections = props.modelValue.LXvalModel.connections.filter(item => (item.id != event.lineId[0][0]));
                    drawIsAnyLineFn()
                };

            } else if (selectList.status == event.status && event.status == _STATUS) { // 都没连 直接连线
                drawIsAnyLineFn()
                // console.log(5555555);
            };
        }
    };
    isAnyLineFn[props.modelValue.LXvalModel.isAnyChange ? "1" : "2"]();
    selectList.active = 0;
    // console.log(props.modelValue.LXvalModel);

};

/** 创建连线
 * @param events 左边模块Id
 * @param event 右边模块Id
 */
const _drawLine = (events, event) => {
    const answerDisplay = document.getElementById('answerDisplayId')

    let line = document.createElement("div");
    line.setAttribute("class", "line");
    line.setAttribute("id", events + '_' + event);

    let triangleLineA = endRight.left - beginLeft.right;
    let triangleLineB = endRight.top - beginLeft.top;
    let angle = Math.atan2(triangleLineB, triangleLineA) * 180 / Math.PI;

    line.style.width = Math.sqrt(Math.pow(Math.abs(triangleLineA), 2) + Math.pow(Math.abs(triangleLineB), 2)) + 'px';
    line.style.top = beginLeft.top + 'px';
    line.style.left = beginLeft.right + 'px';
    line.style.webkitTransformOrigin = "0 50%";
    line.style.mozTransformOrigin = "0 50%";
    line.style.msTransformOrigin = "0 50%";
    line.style.oTransformOrigin = "0 50%";
    line.style.transformOrigin = "0 50%";
    line.style.position = 'absolute';
    line.style.border = '0.08rem solid #09f';
    line.style.borderRadius = '0.7rem';
    line.style.webkitTransform = "rotate(" + angle + "deg)";
    line.style.mozTransform = "rotate(" + angle + "deg)";
    line.style.msTransform = "rotate(" + angle + "deg)";
    line.style.oTransform = "rotate(" + angle + "deg)";
    line.style.transform = "rotate(" + angle + "deg)";
    answerDisplay.appendChild(line)
};


/** 删除连线 以及连线数据
 *  @param {Array} event 两端连线id
 */
const _rmAnswerLine = (event) => {
    let leftObj = props.modelValue.LXvalModel.list.left.filter(item => item.aw == event[0])[0];
    let rightObj = props.modelValue.LXvalModel.list.right.filter(item => item.aw == event[1])[0];
    // props.modelValue.LXvalModel.connections = props.modelValue.LXvalModel.connections.filter(item => item.id != event[0]);
    leftObj.status = rightObj.status = _STATUS;
    // leftObj.lineId = rightObj.lineId = null;
    removeElement(document.getElementById(leftObj.aw + '_' + rightObj.aw));
};

const leftClass = (event) => {
    if (event.active == _LINELEFT) {
        return 'acrfocus'
    } else if (event.status == STATE_CONNECTION) {
        return 'lineToStatus'
    } else {
        return ''
    }
};
/** 数据裂变 */
const model = () => {
    let id = nanoIds(6);

    return {
        "aw": id,
        "text": '',
        "status": 0,
        "active": 0,
        "height": 80,

    }
};
// change事件函数
const onChange = (e, e2, $event) => {
    const obj = {
        "1": () => {
            let a = props.modelValue.LXvalModel.list.left.filter(item => item.aw == e.aw)[0];
            a.text = $event;
        },
        "2": () => {
            let a = props.modelValue.LXvalModel.list.right.filter(item => item.aw == e.aw)[0];
            a.text = $event;
        }
    };
    obj[e2]();
    let rectGetDom = document.getElementById(e.aw);
    let rect;
    requestAnimationFrame(() => {
        rect = rectGetDom.getClientRects()[0];
        props.modelValue.LXvalModel.connections.map(item => {
            removeElement(document.getElementById(item.id + '_' + item.result));
        });
        e.height = rect.height;
        onInitList()
    });
}

/** 增加连线函数对象 */
const addLineList = () => {
    props.modelValue.LXvalModel.list.left.push(model());
    props.modelValue.LXvalModel.list.right.push(model());
};
/** 删除当前条数据 */
const delLineList = (event, num) => {
    // 加一个提示 是否确认删除
    const obj = {
        "1": () => {
            props.modelValue.LXvalModel.list.left = props.modelValue.LXvalModel.list.left.filter(item => item.aw != event.aw);
            props.modelValue.LXvalModel.connections = props.modelValue.LXvalModel.connections.filter(item => item.id != event.aw)
        },
        "2": () => {
            props.modelValue.LXvalModel.list.right = props.modelValue.LXvalModel.list.right.filter(item => item.aw != event.aw)
            // props.modelValue.LXvalModel.connections = props.modelValue.LXvalModel.connections.filter(item => item.result != event.aw);

        }
    };

    props.modelValue.LXvalModel.connections.map(item => {
        item.result.map(itemChild => {
            removeElement(document.getElementById(item.id + '_' + itemChild));

        })
    });

    if (event.lineId && event.lineId.length) {
        if (num == "1") {
            // 左侧 [a, [] ]
            event.lineId[1].map(item => { // item : 右侧 aw
                let ls = props.modelValue.LXvalModel.list.right.filter(itemChild => item == itemChild.aw)[0];
                ls.lineId[0] = ls.lineId[0].filter(item2 => item2 != event.aw);
                if (!ls.lineId[0].length) {
                    ls.lineId = null;
                    ls.status = _STATUS;
                }
            })
        } else { // num == 2
            // 要删除 connections 以及对应的 左侧 lineId 里面的id
            event.lineId[0].map(item => {
                // 筛选出的左侧 对象 把他lineId里面对应的 event.aw 删掉
                let ls = props.modelValue.LXvalModel.list.left.filter(itemChild => item == itemChild.aw)[0];
                ls.lineId[1] = ls.lineId[1].filter(itemChild => itemChild != event.aw);
                if (!ls.lineId[1].length) {
                    ls.lineId = null;
                    ls.status = _STATUS;
                };
                let ls2 = props.modelValue.LXvalModel.connections.filter(itemChild => itemChild.id == ls.aw)[0];
                ls2.result = ls2.result.filter(itemChild => itemChild != event.aw);
                if (!ls2.result.length) {
                    ls2 = null
                }
            })
        }
    };
    obj[num]();
    onInitList();

};
/** 删除节点 */
const removeElement = (_element) => {
    var _parentElement = _element.parentNode;
    if (_parentElement) {
        _parentElement.removeChild(_element);

    }
};

</script>
  
<style scoped lang="scss">
.tigan {
    border-bottom: 1px dashed #dcdfe8;
    padding-bottom: 20px;
    margin-bottom: 10px;
}

ul,
li {
    list-style: none;
}

li {
    margin-top: 10px;
}

header {
    font-size: 14px;

    &>span {
        color: #6d6b6b;
    }
}

article {
    margin-top: 20px;
    margin-left: 88px;
}

.el-input {
    width: 200px;
}

.liStyle {
    display: flex;
    align-items: center;
}

.acrfocus {
    border-color: #F08F4D !important;
    box-shadow: 0 0 7px #f08e4da6;
}



.icon {
    width: 1.2em;
    height: 1.2em;
    vertical-align: -0.1em;
    fill: currentColor;
    overflow: hidden;
    cursor: pointer;
}

.delClass {
    width: 30px;
    height: 30px;
    border: 1px solid #cccccc;
    display: flex;
    justify-content: center;
    align-items: center;
    border-radius: 50%;
    box-shadow: 0 0 4px #dfdfdf;
    margin-left: 5px
}

.answerDisplay {
    // display: flex;
    position: relative;
    width: 60%;
    min-height: 400px;

    // justify-content: space-between;
    .line {
        position: absolute;
        border: 0.08rem solid #09f;
        border-radius: 0.7rem;
    }

    div {
        width: 38%;
        padding: 10px;
        border: 1px solid #b9b9b9;
        border-radius: 3px;
        min-height: 80px;
        max-height: 250px;
        position: absolute;
        // margin-top: 40px;
        display: flex;
        cursor: pointer;
        box-sizing: border-box;
        word-break: break-all;
        white-space: normal;
        overflow: auto;
        display: flex;
        justify-content: center;
        align-items: center;
        background-image: linear-gradient(to bottom, #dcdfe7, #ffffff);
        box-shadow: 0 0 5px #cccccc;

        & * {
            max-width: 100%;
        }

    }
}



.borderDix {
    border-bottom: 0.06897rem dashed #dcdfe8;
    padding-bottom: 1.37931rem;
    margin-bottom: 0.68966rem;
}

.lineToStatus {
    border: 1px solid #61a0ff !important;
    background-image: linear-gradient(to bottom, #e8f0ff, #ffffff) !important;
}
</style>